package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type country struct {
	iCountry store.ICountry
}

var Country = &country{
	iCountry: postgres.Country,
}

func (a *country) init() func() {
	return func() {}
}

func (a *country) onEvent(*event.Data) {}

// Create 创建
func (a *country) Create(ctx context.Context, in *model.CountryCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildCountry(in)
	_, err = a.iCountry.Create(ctx, c)
	return err
}

// Update 更新
func (a *country) Update(ctx context.Context, in *model.CountryUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.CountryCode != nil {
		dict["country_code"] = in.CountryCode
	}

	if in.EnglishName != nil {
		dict["english_name"] = in.EnglishName
	}

	if in.ChineseName != nil {
		dict["chinese_name"] = in.ChineseName
	}

	if in.LocalName != nil {
		dict["local_name"] = in.LocalName
	}

	if in.Location != nil {
		dict["location"] = in.Location
	}

	if in.LocalLanguage != nil {
		dict["local_language"] = in.LocalLanguage
	}

	if in.LocalDialect != nil {
		dict["local_dialect"] = in.LocalDialect
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	return a.iCountry.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *country) Delete(ctx context.Context, in *model.CountryDeleteRequest) error {
	return a.iCountry.Delete(ctx, in.Id)
}

// List 列表查询
func (a *country) List(ctx context.Context, in *model.CountryListRequest) (*model.CountryListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Country
		out   = &model.CountryListResponse{}
	)

	if total, list, err = a.iCountry.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.CountrysEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *country) Find(ctx context.Context, in *model.CountryInfoRequest) (*model.CountryInfo, error) {
	var (
		err  error
		data *entity.Country
		out  = &model.CountryInfo{}
	)

	if data, err = a.iCountry.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.CountryEntityToDto(data)
	return out, nil
}

// buildCountry 构建创建数据现场
func buildCountry(in *model.CountryCreateRequest) *entity.Country {
	// todo: check the entity is required
	return &entity.Country{

		CountryCode: in.CountryCode,

		EnglishName: in.EnglishName,

		ChineseName: in.ChineseName,

		LocalName: in.LocalName,

		Location: in.Location,

		LocalLanguage: in.LocalLanguage,

		LocalDialect: in.LocalDialect,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
